﻿'Copyright (c) 2009 Grailtek

'Permission is hereby granted, free of charge, to any person
'obtaining a copy of this software and associated documentation
'files (the "Software"), to deal in the Software without
'restriction, including without limitation the rights to use,
'copy, modify, merge, publish, distribute, sublicense, and/or sell
'copies of the Software, and to permit persons to whom the
'Software is furnished to do so, subject to the following
'conditions:

'The above copyright notice and this permission notice shall be
'included in all copies or substantial portions of the Software.

'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
'EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
'OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
'NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
'HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
'WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
'FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
'OTHER DEALINGS IN THE SOFTWARE.

Imports System.Text
Imports System.Aspect

Public Class DispatchTraceEmitter
    Implements IDispatchListener

    Private Shared _Default As New DispatchTraceEmitter
    Public Shared ReadOnly Property [Default]() As DispatchTraceEmitter
        Get
            Return _Default
        End Get
    End Property

    Private Sub DoTrace(ByVal msg As String)
        Trace.WriteLine(msg, "ExecutorServices")
    End Sub

    Public Sub BeforeDispatch(ByVal Aspect As IAspect, ByVal delegateInfo As DelegateInfo, ByVal args() As Argument) Implements IDispatchListener.BeforeDispatch
        Try
            Dim sb As New StringBuilder
            sb.Append(Aspect.AspectUIName & " """ & Aspect.UIName & """")
            If args.Count > 0 Then
                sb.Append("(")
                For Each arg As Argument In args
                    Dim strVal As String = If(arg.Value Is Nothing OrElse IsDBNull(arg.Value), "(null)", arg.Value.ToString)
                    Dim tagName As String = If(arg.ParamAttribute Is Nothing, arg.Param.Name, arg.ParamAttribute.UIName)
                    sb.Append(String.Format("{0}=""{1}""", tagName, strVal))
                Next
                sb.Append(")")
            End If
            DoTrace(sb.ToString)
        Catch ex As Exception
            Debug.Fail("trace threw an exception: " & ex.Message)
        End Try
    End Sub

    Public Sub AfterDispatch(ByVal Aspect As IAspect, ByVal delegateInfo As DelegateInfo, ByVal args As Argument(), ByVal returnedObject As Object) Implements IDispatchListener.AfterDispatch
        Try
            If delegateInfo.ReturnType Is GetType(Void) Then Return
            If returnedObject Is Nothing OrElse IsDBNull(returnedObject) Then
                DoTrace("   returned object: (""null"")")
            Else
                Dim counter As Integer = 0
                If returnedObject.GetType.IsArray Then
                    Dim objects() As Object = DirectCast(returnedObject, Object())
                    For i As Integer = 0 To objects.GetUpperBound(0)
                        DoTrace(String.Format("   returned object({0}):{1}", i, GetOutputStringFor(objects(i))))
                    Next
                Else
                    DoTrace(String.Format("   returned object:{0}", GetOutputStringFor(returnedObject)))
                End If
            End If
        Catch ex As Exception
            Debug.Fail("trace threw an exception: " & ex.Message)
        End Try
    End Sub

    Private Function GetOutputStringFor(ByVal o As Object) As String
        Dim sb As New System.Text.StringBuilder
        sb.Append("<")
        If o Is Nothing Then
            sb.Append("(null)")
        Else
            Dim t As Type = If(TypeOf o Is IFactoryCreatedImplementor, o.GetType.GetInterfaces.First, o.GetType)
            For Each op As OutputMapping In OutputMapping.GetMappings(t)
                Dim str As String = "(null)"
                Dim val As Object = op.GetValue(o)
                If Not val Is Nothing Then str = val.ToString
                sb.Append(String.Format("{0}:{1} ", op.Name, str))
            Next
        End If
        sb.Append(">")
        Return sb.ToString
    End Function

End Class